package shixun;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet("/forgot-password")
public class ForgotPasswordServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    private static final String DB_URL = "jdbc:mysql://localhost:3306/userdb?useSSL=false&serverTimezone=UTC&characterEncoding=UTF-8";
    private static final String DB_USER = "root";
    private static final String DB_PASSWORD = "123456";

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        String username = request.getParameter("username");
        String tel = request.getParameter("tel");
        String newpassword = request.getParameter("newpassword");

        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            Connection connection = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);

            // 先验证用户名和手机号是否匹配
            String selectSql = "SELECT * FROM users WHERE username =? AND tel =?";
            PreparedStatement selectStatement = connection.prepareStatement(selectSql);
            selectStatement.setString(1, username);
            selectStatement.setString(2, tel);
            ResultSet resultSet = selectStatement.executeQuery();

            if (resultSet.next()) {
                // 如果匹配，更新密码
                String updateSql = "UPDATE users SET password =? WHERE username =? AND tel =?";
                PreparedStatement updateStatement = connection.prepareStatement(updateSql);
                updateStatement.setString(1, newpassword);
                updateStatement.setString(2, username);
                updateStatement.setString(3, tel);
                int rowsAffected = updateStatement.executeUpdate();
                if (rowsAffected > 0) {
                    response.getWriter().println("密码修改成功");
                    response.sendRedirect("/login.jsp");
                } else {
                    response.getWriter().println("密码修改失败");
                }
            } else {
                response.getWriter().println("验证失败，请检查用户名和手机号");
            }

            resultSet.close();
            selectStatement.close();
            connection.close();
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
            response.getWriter().println("忘记密码验证出现异常");
        }
    }
}